package redora.rdo.client.model;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.gen2.table.client.FixedWidthFlexTable;
import com.google.gwt.gen2.table.client.FixedWidthGrid;
import com.google.gwt.gen2.table.client.ScrollTable;
import com.google.gwt.gen2.table.client.SelectionGrid.SelectionPolicy;
import com.google.gwt.gen2.table.override.client.FlexTable.FlexCellFormatter;
import com.google.gwt.http.client.Request;
import com.google.gwt.http.client.RequestBuilder;
import com.google.gwt.http.client.RequestCallback;
import com.google.gwt.http.client.RequestException;
import com.google.gwt.http.client.Response;
import com.google.gwt.http.client.URL;
import com.google.gwt.json.client.JSONArray;
import com.google.gwt.json.client.JSONObject;
import com.google.gwt.json.client.JSONParser;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.CheckBox;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.HasHorizontalAlignment;
import com.google.gwt.user.client.ui.LazyPanel;
import com.google.gwt.user.client.ui.Widget;

public class AttributeFieldsView extends LazyPanel {

	private ScrollTable scrollTable = null;

	String baseUrl = URL.encode(GWT.getModuleBaseURL()
			+ "modelFieldsView.do?action=getFields");

	FlowPanel root = new FlowPanel();

	String objectName = "";

	public AttributeFieldsView(String modelName) {
		this.objectName = modelName;
	}

	@Override
	protected Widget createWidget() {
		// Combine the components into a ScrollTable
		final ScrollTable scrollTable = createScrollTable();

		createDataList();

		// Add the components to the page
		root.add(scrollTable);

		return root;
	}

	/**
	 * Create the scroll table.
	 * 
	 * @return a data table
	 */
	private ScrollTable createScrollTable() {
		FixedWidthFlexTable headerTable = createHeaderTable();
		FixedWidthFlexTable footerTable = createFooterTable();
		FixedWidthGrid dataTable = createDataTable();

		// Combine the components into a ScrollTable
		scrollTable = new ScrollTable(dataTable, headerTable);
		scrollTable.setFooterTable(footerTable);

		// Set some options in the scroll table
		// scrollTable.setSortingEnabled(true);
		scrollTable.setResizePolicy(ScrollTable.ResizePolicy.FILL_WIDTH);
		scrollTable.setSize("100%", "500");

		// Setup some default widths
		scrollTable.setColumnWidth(2, 50);
		scrollTable.setColumnWidth(5, 50);

		// Return the data table
		return scrollTable;
	}

	/**
	 * Create the data table.
	 * 
	 * @return a data table
	 */
	private FixedWidthGrid createDataTable() {
		// Create a new table
		FixedWidthGrid dataTable = new FixedWidthGrid();

		// dataTable.setSelectionPolicy(SelectionGrid.SelectionPolicy.MULTI_ROW);

		dataTable.setSelectionPolicy(SelectionPolicy.CHECKBOX);

		dataTable.resizeColumns(7);

		// Return the data table
		return dataTable;
	}

	/**
	 * Get the User Data List.
	 * 
	 */
	private void createDataList() {
		final FixedWidthGrid dataTable = scrollTable.getDataTable();
		String url = URL.encode(baseUrl + "&objectName=" + objectName);
		RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, url);
		builder.setCallback(new RequestCallback() {
			public void onError(Request request, Throwable exception) {
				Window.alert("upgrade failed!");
			}

			public void onResponseReceived(Request request, Response response) {
				JSONArray jsons = JSONParser.parse(response.getText())
						.isArray();
				copyValue(dataTable, jsons);
			}
		});
		try {
			builder.send();
		} catch (RequestException e) {
			e.printStackTrace();
		}
	}

	/**
	 * Create the footer table.
	 * 
	 * @return a footer table
	 */
	private FixedWidthFlexTable createFooterTable() {
		// Create a new table
		FixedWidthFlexTable footerTable = new FixedWidthFlexTable();
		// FlexCellFormatter formatter = footerTable.getFlexCellFormatter();
		// Return the footer table
		return footerTable;
	}

	/**
	 * Create the header table.
	 * 
	 * @return a header table
	 */
	private FixedWidthFlexTable createHeaderTable() {
		// Create a new table
		FixedWidthFlexTable headerTable = new FixedWidthFlexTable();
		FlexCellFormatter formatter = headerTable.getFlexCellFormatter();

		// Level 1 headers
		// headerTable.setHTML(0, 0, "<b>User Data</b>");
		// formatter.setColSpan(0, 0, 9);
		// formatter.setHorizontalAlignment(0, 0,
		// HasHorizontalAlignment.ALIGN_CENTER);

		final CheckBox selectAll = new CheckBox();
		selectAll.addClickHandler(new ClickHandler() {

			public void onClick(ClickEvent arg0) {
				if (selectAll.getValue()) {
					scrollTable.getDataTable().selectAllRows();
				} else {
					scrollTable.getDataTable().deselectAllRows();
				}
			}

		});
		headerTable.setWidget(0, 0, selectAll);
		formatter.setHorizontalAlignment(0, 0,
				HasHorizontalAlignment.ALIGN_CENTER);
		headerTable.setHTML(0, 1, "field_name");
		formatter.setHorizontalAlignment(0, 1,
				HasHorizontalAlignment.ALIGN_CENTER);

		headerTable.setHTML(0, 2, "field_type");
		formatter.setHorizontalAlignment(1, 2,
				HasHorizontalAlignment.ALIGN_CENTER);
		headerTable.setHTML(0, 3, "not_null");
		formatter.setHorizontalAlignment(1, 3,
				HasHorizontalAlignment.ALIGN_CENTER);
		headerTable.setHTML(0, 4, "finder");
		formatter.setHorizontalAlignment(1, 4,
				HasHorizontalAlignment.ALIGN_CENTER);
		headerTable.setHTML(0, 5, "lazy");
		formatter.setHorizontalAlignment(1, 5,
				HasHorizontalAlignment.ALIGN_CENTER);
		headerTable.setHTML(0, 6, "regexp");
		formatter.setHorizontalAlignment(1, 6,
				HasHorizontalAlignment.ALIGN_CENTER);
		headerTable.setHTML(0, 7, "maxlength");
		formatter.setHorizontalAlignment(1, 7,
				HasHorizontalAlignment.ALIGN_CENTER);

		// Return the header table
		return headerTable;
	}

	private void copyValue(FixedWidthGrid dataTable, JSONArray array) {
		dataTable.resizeRows(array.size());
		for (int i = 0; i < array.size(); i++) {
			JSONObject value = array.get(i).isObject();
			if (value.get("field_name") != null
					&& !value.get("field_name").toString().equalsIgnoreCase(
							"null")) {
				dataTable.setText(i, 0, value.get("field_name").isString()
						.stringValue());
			}
			if (value.get("field_type") != null
					&& !value.get("field_type").toString().equalsIgnoreCase(
							"null"))
				dataTable.setText(i, 1, value.get("field_type").isString()
						.stringValue());
			if (value.get("not_null") != null
					&& !value.get("not_null").toString().equalsIgnoreCase(
							"null")) {
				CheckBox box = new CheckBox();
				box.setValue(Boolean.valueOf(value.get("not_null").isString()
						.stringValue()));
				box.setEnabled(false);
				dataTable.setWidget(i, 2, box);
			}
			if (value.get("finder") != null
					&& !value.get("finder").toString().equalsIgnoreCase("null")) {
				CheckBox box = new CheckBox();
				box.setValue(Boolean.valueOf(value.get("finder").isString()
						.stringValue()));
				box.setEnabled(false);
				dataTable.setWidget(i, 3, box);
			}
			if (value.get("lazy") != null
					&& !value.get("lazy").toString().equalsIgnoreCase("null")) {
				CheckBox box = new CheckBox();
				box.setValue(Boolean.valueOf(value.get("lazy").isString()
						.stringValue()));
				box.setEnabled(false);
				dataTable.setWidget(i, 4, box);
			}
			if (value.get("regexp") != null
					&& !value.get("regexp").toString().equalsIgnoreCase("null"))
				dataTable.setText(i, 5, value.get("regexp").isString()
						.stringValue());
			if (value.get("maxlength") != null
					&& !value.get("maxlength").toString().equalsIgnoreCase(
							"null"))
				dataTable.setText(i, 6, value.get("maxlength").isString()
						.stringValue());
		}
	}

}
